<?php
/*
 *	扫呗接口模块
 */
namespace app\api\controller;

use think\facade\Log;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\TextCard;
use app\common\model\DealMain as D_M;
use app\common\model\DealInfo as INFO_M;
use app\common\model\CustomerMain as CUS_M;
use app\common\service\BillMain as B_S;
use app\common\model\SystemConfig as CONFIG;

class Saobei extends Base{
	private $notify_url='Saobei/notifys';

	public function pay(){
		$number=I('get.n');
		$key=I('get.k');
		$url='';
		$T=D_M::info(['number'=>$number]);
		if($T==''){
			$this->error('该订单不存在',null,'',0);
			return false;
		}
		
		$en_key=\core\Encode::lcsw_notify_key($T['id']);
		if($key!=$en_key){
			$this->error('该订单不存在!');
			return false;
		}

		if($T['status']==1){
			$this->error('该订单已支付');
			return false;
		}
		
		$conf=CONFIG::get('api.lcsw');
		if(empty($conf)) $this->error('请先配置扫码支付参数');
		
		if(!$conf['pay_switch']) $this->error('请先开启扫码付款功能');

		//设置回调地址
		$notify_url=U($this->notify_url,['ssid'=>I('get.ssid')],true);
		$notify_url=str_replace("https://","http://",$notify_url);
		$conf['notify_url']=$notify_url;
		
		$lcsw_obj=new \Lcsw($conf);
		$res=$lcsw_obj->create_qrcode_pay($T);
		if($res['errno']==0){
			$url=$res['data'];
		}else{
			$this->error($res['data'],0);
		}
		
		return $this->fetch('',[
			'url'=>$url,
			'T'=>$T,
		]);
	}
	
	// 回调函数
	public function notifys(){
		$log_name= 'notify';
		$jsonstr = file_get_contents("php://input");
		
		// $jsonstr='{"attach":"lcsw|2589|48fd3377","channel_trade_no":"2022103022001456971448039472","end_time":"20221030161609","key_sign":"8eff8d24da6ae6d181ff75756a678c7b","merchant_name":"东莞市海帆纺织有限公司","merchant_no":"860205949000013","out_trade_no":"183092147622322103016160405141","pay_type":"020","receipt_fee":"112000","result_code":"01","return_code":"01","return_msg":"支付成功","terminal_id":"18309214","terminal_time":"20221030161554","terminal_trace":"221030161202284","total_fee":"112000","user_id":"2088912655356970"}';
		
		if($jsonstr==''){
			$this->trace($log_name,'非法访问！');
			return;
		}
		
		$uuid=I('get.ssid',0);
		if($uuid===0){
			$this->trace($log_name,'ssid丢失，无法访问！');
			return;
		}
		
		$result  = json_decode($jsonstr,true);
		$info    = explode('|',$result['attach']);
		$id		 = $info[1];
		$key     = $info[2];
		if($info[0]=='lcsw'){
			$key2=\core\Encode::lcsw_notify_key($id);
			if($key!=$key2){
				$this->trace($log_name,'校验失败！',$jsonstr);
				return 'error';
			}else{			
				$lcsw_conf=CONFIG::get('api.lcsw');
				$T=D_M::info(['id'=>$id,'uuid'=>$uuid]);
				if($T=='' || $T['number']!=$result['terminal_trace']){
					$this->trace($log_name,'订单不存在！',$jsonstr);
					return 'error';
				}
				if($lcsw_conf['merchant_no']!=$result['merchant_no'] || $lcsw_conf['terminal_id']!=$result['terminal_id']){
					$this->trace($log_name,'参数有误！',$jsonstr);
					return 'error';
				}
				
				if($T['status']==1 && $T['is_olpay']==1){
					$this->trace($log_name,'回调已处理！',$jsonstr);
					return 'ok';
				}

				//校验订单金额是否正确
				$lcsw=new \Lcsw($lcsw_conf);
				$T['tag']=$result['out_trade_no'];
				$check_res=$lcsw->check_pay($T);
				if($check_res['errno']==0 ){
					if($check_res['data']['total_fee']==$T['total']*100){
						
						switch ($result['pay_type']) {
							case '010':
								$pay_type='wechat';
								$pay_name='微信支付';
								break;
							case '020':
								$pay_type='alipay';
								$pay_name='支付宝';
								break;
							case '060':
								$pay_type='qq';
								$pay_name='QQ钱包';
								break;
							case '080':
								$pay_type='jd';
								$pay_name='京东钱包';
								break;
							case '110':
								$pay_type='yinlian';
								$pay_name='银联二维码';
								break;
							case '160':
								$pay_type='shuzi';
								$pay_name='数字人民币';
								break;
							default:
								$pay_type = 'other';
								$pay_name='其他支付';
								break;
						}
						
						$poundage=price_one($T['total']*$lcsw_conf['poundage']);
						$data=[
							'poundage'	=>	$poundage,
							'paytype'	=>	'扫呗支付',
							'is_olpay'	=>	1,
							'olpay_type'=>	$pay_type,
							'tag'		=>	$result['out_trade_no'],
							'status'	=>	1,
						];
						D_M::where('id',$id)->save($data);
						B_S::up_bill($id,$uuid);
						
						$T['paytype']=$pay_name;
						// 发送消息通知
						$this->paymentMessage($T);
						$this->trace($log_name,$T['number'].' 回调成功！',$jsonstr);
						return 'ok';
					}else{
						$this->trace($log_name,'交易金额不正确！',$jsonstr);
					}
				}else{
					return $check_res['data'];
				}
			}
		}
		return 'error';
	}
	
	// 付款成功后发起通知
	protected function paymentMessage($T){
		$this->gzhMessage($T);
		$this->qiyeWxMessage($T);
	}
	
	// 公众号消息通知
	protected function gzhMessage($deal){
		$gzh=CONFIG::get('api.gzh');
		//判断是否发送消息
		if(intval($gzh['message']['payment']['on'])===0) return;
		
		$wechat = Factory::officialAccount($gzh['option']);
		$openid=explode(",",$gzh['message']['payment']['openid']);
		$ids=\core\Encode::order_codeid($deal['id']);		
		
		foreach($openid as $pid){
			$data=[
				"touser"=>$pid,
				"template_id"=>$gzh['message']['payment']['tplid'],
				"url"=>U('Saobei/order',['ids'=>$ids,'num'=>$deal['number'],'ssid'=>$deal['uuid']],true),
				"topcolor"=>"#FF0000",
				"data"=>[
					"first"=>[
						"value"=>"您有一位客户付款成功，请尽快安排发货",
						"color"=>"#173177"	 //参数颜色
					],
					"keyword1"=>[
						"value"=>$deal['number'],
						"color"=>"#173177"
					],
					"keyword2"=>[
						"value"=>$deal['paytype'],
						"color"=>"#173177"
					],
					"keyword3"=>[
						"value"=>"￥".$deal['total']."元",
						"color"=>"#CC0033"
					],
					"keyword4"=>[
						"value"=>$deal['customer']['name'],
						"color"=>"#CC0033"
					],
					"keyword5"=>[
						"value"=>date('Y-m-d H:i'),
						"color"=>"#173177"
					],
					"remark"=>[
						"value"=>"详情请点击链接查看",
						"color"=>"#173177"
					]
				]
			];
			$wechat->template_message->send($data);
		}
	}
	
	// 付款成功后发起企业通知
	protected function qiyeWxMessage($deal){	
		$qiyewx=CONFIG::get('api.qiyewx');
		//判断是否发送消息
		if(intval($qiyewx['message']['payment']['on'])===0) return;
		//强制转化数字，否则报错
		$qiyewx['option']['agent_id']=intval($qiyewx['option']['agent_id']);
		$wechat = Factory::work($qiyewx['option']);
		$touser=explode("|",$qiyewx['message']['payment']['touser']);	//通知成员
		$toparty=explode("|",$qiyewx['message']['payment']['toparty']);	//通知部门
		$ids=\core\Encode::order_codeid($deal['id']);
		
		// 获取 Messenger 实例
		$messenger = $wechat->messenger;		
		
		// 循环通知成员
		foreach($touser as $user_val){
			$message = new TextCard($this->qiyeMessageArray($deal,$ids));
			$res=$messenger->message($message)->toUser($user_val)->send();
		}
		
		// 循环通知部门
		foreach($toparty as $party_val){
			$message = new TextCard($this->qiyeMessageArray($deal,$ids));
			$res=$messenger->message($message)->toParty($party_val)->send();
		}
	}
	
	//生成企业微信通知模板数组
	protected function qiyeMessageArray($deal,$ids){
		$data=[
			'title' => '客户付款通知',
			'description' => '
			<div class="gray">您的客户【 '.$deal['customer']['name'].' 】付款成功，请尽快安排发货</div>
			<div class="normal">交易流水：'.$deal['number'].'</div>
			<div class="normal">付款方式：'.$deal['paytype'].'</div>
			<div class="highlight">付款金额：'.$deal['total'].'元</div>
			<div class="highlight">客户昵称：【 '.$deal['customer']['name'].' 】</div>
			<div class="normal">支付时间：'.date('Y-m-d H:i').'</div>', 
			'url' => U('Saobei/order',['ids'=>$ids,'num'=>$deal['number'],'ssid'=>$deal['uuid']],true)
		];
		return $data;
	}

	// 付款成功通知跳转订单明细
	public function order(){
		$number=I('get.num');
		$ids=I('get.ids');
		$uuid=I('get.ssid',0);

		$T=D_M::where(['number'=>$number,'uuid'=>$uuid])->find();
		if($T!=''){
			$id=$T['id'];
			$key=\core\Encode::order_codeid($id);
			if($ids!=$key){
				$this->error('参数有误！',0);	
			}else{
				$info=INFO_M::listData($id);
				return $this->fetch('',[
					'T'=>$T,
					'info'=>$info,
				]);
			}
		}else{
			$this->error('订单不存在或已删除！',0);
		}
	}
}
?>